import type { UserModelState } from '@/models/userModel';
import { qqBinding, qqCallback } from '@/services/user';
import useRequest from '@ahooksjs/use-request';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import type { ConnectRC } from '@umijs/max';
import { connect, history, useModel, useSearchParams } from '@umijs/max';
import { message, Modal } from 'antd';
import { forwardRef, useEffect } from 'react';
import styles from './index.less';

interface Props {
  refInstance: any;
  usermodel: UserModelState;
}

const { confirm } = Modal;
const Index: ConnectRC<Props> = (props) => {
  const { dispatch } = props;
  const [urlParams] = useSearchParams();
  const { initialState, setInitialState, refresh } = useModel('@@initialState');
  const { run: qqCallbackRun } = useRequest(qqCallback, {
    manual: true,
    onSuccess: async (res) => {
      const { code: resCode, message: resMessage, data: resData } = res;
      if (resCode === 200) {
        // token过期时间
        resData.tokenSurvivalTime = Date.now() + resData.expires_in * 1000;
        // 缓存到本地
        localStorage.setItem(BASE_TOKEN_NAME, JSON.stringify(resData));
        const {
          code,
          message: messageText,
          data,
        } = (await initialState?.fetchUserInfo?.(
          'login',
        )) as unknown as COMMON.BaseSuccess<HOMEAPI.CurrentUser>;
        if (code === 200) {
          message.success('登录成功!');
          await setInitialState((s: any) => ({
            ...s,
            currentUser: data,
          }));
          refresh();
          dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: false });
          history.push('/plaza');
        } else {
          confirm({
            title: '登录异常',
            icon: <ExclamationCircleOutlined />,
            content: messageText,
            okText: '确认',
            onOk: () => {
              window.close();
            },
            onCancel: () => {
              window.close();
            },
          });
        }
      } else {
        confirm({
          title: '登录异常',
          icon: <ExclamationCircleOutlined />,
          content: resMessage,
          okText: '确认',
          onOk: () => {
            window.close();
          },
          onCancel: () => {
            window.close();
          },
        });
      }
    },
  });

  const { run: qqBindingRun } = useRequest(qqBinding, {
    manual: true,
    onSuccess: async (res) => {
      const { code, message: msg } = res;
      if (code === 200) {
        message.success('绑定成功');
        history.push('/admin/user/account/settings');
      } else {
        message.error(msg);
      }
    },
  });

  useEffect(() => {
    const state = urlParams.get('state');
    const code = urlParams.get('code');
    const processMode = localStorage.getItem('processMode');
    if (state && code) {
      const params: USERAPI.QQLoginT = {
        state: state,
        code: code,
      };
      if (processMode === 'qqbind') {
        qqBindingRun(params);
      } else {
        qqCallbackRun(params);
      }
    }
  }, []);
  return <div className={styles.qqLoginWrap}>正在登录中....</div>;
};

export default connect(({ usermodel }: { usermodel: UserModelState }) => ({
  usermodel,
}))(forwardRef((props: any, ref) => <Index {...props} refInstance={ref} />));
